package com.uca.sisbec.actions.becario;

import com.uca.sisbec.commons.HibernateAction;
import com.uca.sisbec.forms.becario.ComentarioForm;
import com.uca.sisbec.helpers.becario.ComentarioHelper;
import com.uca.sisbec.mapping.Becario;
import com.uca.sisbec.mapping.Usuario;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ComentarioAction extends HibernateAction{
    public ActionForward init(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (!isBecarioInSession(request)) return mapping.findForward("searchBecario");
        setOptionsList(request);
        return mapping.findForward("success");
    }
    
    public ActionForward saveComment(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        ComentarioForm cf = (ComentarioForm) form;
        ComentarioHelper helper = new ComentarioHelper(getSession(request));
        String carnet = ((Becario)request.getSession().getAttribute("_BECARIO")).getCarnet(),
                alias = ((Usuario)request.getSession().getAttribute("_USER")).getAlias(),
                comment = cf.getComentario();
        helper.saveComment(carnet, alias, comment);
        cf.setComentario("");
        cf.setId(0);
        setOptionsList(request);
        return mapping.findForward("success");
    }
    
    public ActionForward deleteComment(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        ComentarioForm cf = (ComentarioForm) form;
        ComentarioHelper helper = new ComentarioHelper(getSession(request));
        int id = cf.getId();
        helper.deleteComment(id);
        cf.setComentario("");
        cf.setId(0);
        setOptionsList(request);
        return mapping.findForward("success");
    }

    private void setOptionsList(HttpServletRequest request) {
        ComentarioHelper helper = new ComentarioHelper(getSession(request));
        request.setAttribute("commentsList", helper.getCommentsByUser(request));
    }
}
